/*
 *   项目名称：rpc-demo
 *   文件名称：com.xiaolon.example.consumer.UserServiceProxy
 *
 *   创建人：  ZHOU XIAO LONG
 *   创建日期：2024/12/3
 *
 */
package com.xiaolon.example.consumer;

import cn.hutool.http.HttpResponse;
import com.xiaolon.example.common.model.User;
import com.xiaolon.example.common.service.UserService;
import com.xiaolon.rpc.model.RpcRequest;
import com.xiaolon.rpc.model.RpcResponse;
import com.xiaolon.rpc.serializer.JdkSerializer;
import com.xiaolon.rpc.serializer.Serializer;
import cn.hutool.http.HttpRequest;

import java.io.IOException;


/*
 * 类描述：UserServiceProxy
 * 静态代理实现
 */
public class UserServiceProxy implements UserService {
    @Override
    public User getUser(User user) {
        // 指定序列化器
        Serializer serializer = new JdkSerializer();

        // 构造http请求
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(UserService.class.getName())
                .methodName("getUser")
                .parameterTypes(new Class[]{User.class})
                .args(new Object[]{user})
                .build();

        try{
            // 序列化请求
            byte[] bodyBytes = serializer.serialize(rpcRequest);
            byte[] result;
            try(HttpResponse httpRequest = HttpRequest.post("http://localhost:8080")
                    .body(bodyBytes)
                    .execute()){
                result = httpRequest.bodyBytes();
            }
            RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
            return (User)rpcResponse.getData();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;

    }
}
